package com.ideaplugin.datamanager.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.ideaplugin.datamanager.entity.SysUser;
import com.ideaplugin.datamanager.entity.SysUserRole;
import com.ideaplugin.datamanager.manager.SysUserManager;
import com.ideaplugin.datamanager.manager.SysUserRoleManager;
import com.ideaplugin.datamanager.model.common.CommonResultCode;
import com.ideaplugin.datamanager.model.common.DwhException;
import com.ideaplugin.datamanager.model.common.UserInfo;
import com.ideaplugin.datamanager.model.request.ChangePasswordParam;
import com.ideaplugin.datamanager.model.request.LoginUserParam;
import com.ideaplugin.datamanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

import static com.ideaplugin.datamanager.entity.table.SysUserRoleTableDef.SYS_USER_ROLE;
import static com.ideaplugin.datamanager.entity.table.SysUserTableDef.SYS_USER;

/**
 * Created on 2023/11/30.
 *
 * @author zhaojb
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private SysUserManager sysUserManager;
    @Autowired
    private SysUserRoleManager userRoleManager;

    @Override
    public boolean login(LoginUserParam user) {
        final SysUser sysUser = sysUserManager.queryChain()
                .from(SysUser.class)
                .where(SYS_USER.LOGIN_NAME.eq(user.getUsername()))
                .one();
        if (Objects.isNull(sysUser)) {
            throw new DwhException(CommonResultCode.EXCEPTION.code, "用户不存在");
        }
        if (Objects.equals(user.getPassword(), sysUser.getPassword())) {
            StpUtil.login(sysUser.getUserId());
            final UserInfo userInfo = BeanUtil.copyProperties(sysUser, UserInfo.class);
            final List<Long> roleIds = userRoleManager.queryChain()
                    .from(SysUserRole.class)
                    .select(SYS_USER_ROLE.ROLE_ID)
                    .where(SYS_USER_ROLE.USER_ID.eq(sysUser.getUserId()))
                    .listAs(Long.class);
            userInfo.setRoleIds(roleIds);
            StpUtil.getSession().set(SaSession.USER, userInfo);
            return true;
        }
        return false;
    }

    @Override
    public boolean changePassword(ChangePasswordParam changePasswordParam) {
        final Object userId = StpUtil.getLoginId();
        final SysUser sysUser = sysUserManager.queryChain()
                .from(SysUser.class)
                .where(SYS_USER.USER_ID.eq(userId))
                .one();
        if (!Objects.equals(changePasswordParam.getOldPassword(), sysUser.getPassword())) {
            throw new DwhException(CommonResultCode.EXCEPTION.code, "当前密码错误");
        }
        sysUser.setPassword(changePasswordParam.getPassword());
        return sysUserManager.updateById(sysUser);
    }
}
